package ged.extension.point.definition.handlers;

import ged.Node;
import ged.extension.point.definition.IFigureFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;

public class EvaluateContributionsHandler {
	//Access any extensions that have been created for this extension point
	private static final String ICUSTOM_SHAPE_ID = 
			"ged.extension.point.definition.custom_shape";
	static Map<String, Map<IFigure, WrappingLabel>> map=new HashMap<String, Map<IFigure, WrappingLabel>>();
	private static EvaluateContributionsHandler instance = null;
	private IMapMode mapMode;
	private Node node;
	
	
	protected EvaluateContributionsHandler()
	{
		
	}
	
	public static EvaluateContributionsHandler getInstance()
	{
		if(instance == null)
		{
			instance = new EvaluateContributionsHandler();
		}
		return instance;
	}
	
	
	
	public Map<String, Map<IFigure, WrappingLabel>> evaluate(Node node, IMapMode mapMode) {
		this.mapMode = mapMode;
		this.node = node;
		//Extension Registry - API which returns the extension points - Get Extension Registry
		IExtensionRegistry registry = Platform.getExtensionRegistry();
		//Read all the extension
		/**
		 * Configuration elements are object representations of the XML elements under the <extension> tag in the plugin.xml files
		 */
		IConfigurationElement[] config = registry
				.getConfigurationElementsFor(ICUSTOM_SHAPE_ID);
		//for (IConfigurationElement configElement : config)
		Map<IFigure, WrappingLabel> returnedMap = new HashMap<IFigure, WrappingLabel>();
		for (int i = 0; i < config.length; i++) 
		{
			System.out.println("Evaluating extension");
			IConfigurationElement element = config[i];
			String name = element.getAttribute("name");
			//String uniqueID = element.getAttribute("id");
			try {
				final Object factory = element.createExecutableExtension("class");
				if(((IFigureFactory) factory).canCreate(name))
					returnedMap = ((IFigureFactory) factory).createIFigure(node, mapMode);  
				else 
					returnedMap = null;
			} catch (CoreException e) {
				e.printStackTrace();
			}
			map.put(name, returnedMap);	
		}
		return map;

	}
	
	public String isolateProjectName(String path_name)
	{
		String nospaces = path_name.trim();
		String[] split_string = nospaces.split("\\.");
		for(int i=0; i<split_string.length-1; i++)
			System.out.println(split_string[i]);
		//int length_of_split_string = split_string.length;
		String extractedProjectName = split_string[split_string.length-1];
		
		return extractedProjectName;
	}	
}
